<template>
  <div class="buttonWrap">
    <template v-if="from == 'table'">
      <a-tooltip placement="top" :title="ids ? '编辑' : ''">
        <a-button @click="handClick" :type="ids ? 'link' : 'primary'" :size="ids ? 'small' : 'default'">
          <span v-if="ids">
            <Icons type="edit"></Icons>
          </span>
          <span v-else>新增</span>
        </a-button>
      </a-tooltip>
    </template>
    <template v-else-if="from == 'tree'">
      <template v-if="fromType == 'edit'">
        <a-tooltip title="编辑">
          <a-button @click="handClick" type="link" size="small">
            <Icons class="iconButton" type="edit" />
          </a-button>
        </a-tooltip>
      </template>
      <template v-else-if="fromType == 'add'">
        <a-tooltip title="新增">
          <a-button @click="handClick" type="link" size="small">
            <Icons class="iconButton" type="plus" />
          </a-button>
        </a-tooltip>
      </template>
    </template>
    <a-drawer :title="drawerTitle" placement="right" :closable="true" :visible="visible" @close="onClose" :width="600">
      <div class="drawContWrap">
        <a-spin :spinning="loading.getLoading" class="spinWrap">
          <a-form :form="form">
            <a-row>
              <a-col :span="item.colSpan" v-for="item in formData" :key="item.dataIndex">
                <FormItem :formVal="formVal" :formData="formData" :item="item" :form="form">
                </FormItem>
              </a-col>
            </a-row>
          </a-form>
        </a-spin>
      </div>
      <div :style="{
        position: 'absolute',
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e8e8e8',
        padding: '10px 16px',
        textAlign: 'right',
        left: 0,
        background: '#fff',
        borderRadius: '0 0 4px 4px',
      }">
        <a-space>
          <a-button @click="onClose"> 取消 </a-button>
          <a-button type="primary" @click="onClickSave" :loading="loading.saveLoading">
            保存
          </a-button>
        </a-space>
      </div>
    </a-drawer>
  </div>
</template>
<script>
import Icons from "./Icons.vue";
import FormItem from "./FormItem.vue";
import { formDataMatter } from "./js/js";
export default {
  name: "AddButton",
  components: {
    Icons,
    FormItem,
  },
  props: {
    // 菜单id
    menuId: {
      type: [String, Number],
    },
    // 数据
    ids: {
      type: [String, Number],
    },
    headTitle: {
      type: [String, Number],
    },
    onRefresh: {
      type: Function,
      default: () => { },
    },
    from: {
      type: String,
      default: "table",
    },
    fromType: {
      type: String,
      default: "edit",
    },
    aParams: {
      type: [Object],
      default: () => { },
    },
  },
  data() {
    return {
      visible: false,
      drawerTitle: "",
      form: null,
      formData: [],
      formVal: {},
      loading: {
        getLoading: false,
        saveLoading: false,
      },
      isChange: false,
    };
  },
  methods: {
    handClick() {
      this.getHeadTitle();
      this.visible = true;
      this.getFormData();
    },
    onClose() {
      if (this.isChange) {
        this.$confirm({
          title: "提示信息",
          content: "当前页面数据未保存，确定退出吗？",
          cancelText: "取消",
          okText: "确定",
          onOk: () => {
            this.visible = false;
          },
          onCancel: () => { },
          class: "test",
        });
      } else {
        this.visible = false;
      }
    },
    getFormData() {
      let params = {};
      let url;
      if (Number(this.menuId) == 6) {
        url = this.$getuserinfoTable;
        params["userid"] = this.ids;
      } else if (Number(this.menuId) == 7) {
        url = this.$getmenuroleinfo;
        params["roleId"] = this.ids;
      } else if (Number(this.menuId) == 8) {
        url = this.$getdeptdatainfo;
        params["roleId"] = this.ids;
      } else if (Number(this.menuId) == 9) {
        url = this.$getformmenudiytreeinfo;
        params["id"] = this.ids;
      } else if (Number(this.menuId) == 13) {
      } else if (Number(this.menuId) == 16) {
        url = this.$getTemplate;
        params["flowTypeId"] = this.ids;
      } else if (Number(this.menuId) == 91) {
        url = this.$getProcessNodeTemplate;
        if (this.ids) {
          params["id"] = this.ids;
        } else {
        }
      } else if (Number(this.menuId) == 92) {
        url = this.$getChatGroupTemplate;
        if (this.ids) {
          params["id"] = this.ids;
        } else {

        }
      } else if (Number(this.menuId) == 994) {
        url = this.$addOrUpdateTemplate;
        if (this.ids) {
          params["id"] = this.ids;
        } else {
        }
      } else if (Number(this.menuId) == 995) {
        url = this.$addOrUpdateTemplateQG;
        if (this.ids) {
          params["id"] = this.ids;
        } else {
        }
      } else if (Number(this.menuId) == 996) {
        url = this.$pageDongkuangDangerEquipmentAddOrUpdateTemplate;
        if (this.ids) {
          params["id"] = this.ids;
        } else {
        }
      } else if (Number(this.menuId) == 977) {
        url = this.$mhqtzAddOrUpdateTemplate;
        if (this.ids) {
          params["id"] = this.ids;
        } else {
        }
      }
      params = {
        ...params,
        ...this.aParams,
      };
      // 校验 
      if (!params['company'] && [977].includes(Number(this.menuId)) && !this.ids) {
        this.$message.error("请选择左侧公司");
        this.visible = false;
        return;
      }
      if (!url) {
        return;
      }
      this.loading = {
        ...this.loading,
        getLoading: true,
      };
      this.getAxios(url, params)
        .then((res) => {
          if (res.code == 200) {
            let data = res.data;
            this.formData = data.dataList;
            this.formVal = formDataMatter("in", data.defVal, data.dataList);
            this.$nextTick(() => {
              this.form.setFieldsValue(this.formVal);
            });
          } else {
            this.$message.error(res.msg || "操作失败");
            this.visible = false;
          }
        })
        .finally(() => {
          this.loading = {
            ...this.loading,
            getLoading: false,
          };
        });
    },
    onClickSave() {
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          let tempVal = formDataMatter("out", values, this.formData);
          let params = {
            ...tempVal,
          };
          let url;
          if (Number(this.menuId) == 6) {
            url = this.$addsguser;
            params["userid"] = this.ids;
          } else if (Number(this.menuId) == 7) {
            url = this.$addmenurole;
            params["roleId"] = this.ids;
          } else if (Number(this.menuId) == 8) {
            url = this.$adddeptdatarole;
            params["roleId"] = this.ids;
          } else if (Number(this.menuId) == 9) {
            url = this.$addformmenudiytree;
          } else if (Number(this.menuId) == 13) {
            url = "";
          } else if (Number(this.menuId) == 16) {
            url = this.$addOrUpdate;
          } else if (Number(this.menuId) == 91) {
            url = this.$addOrUpdateProcessNode;
            if (this.ids) {
              params["id"] = this.ids;
            }
          } else if (Number(this.menuId) == 92) {
            url = this.$addOrUpdateChatGroup;
            if (this.ids) {
              params["id"] = this.ids;
            }
          } else if (Number(this.menuId) == 994) {
            url = this.$addOrUpdateMHQ;
            if (this.ids) {
              params["id"] = this.ids;
            }
          } else if (Number(this.menuId) == 995) {
            url = this.$addOrUpdateQG;
            if (this.ids) {
              params["id"] = this.ids;
            }
          } else if (Number(this.menuId) == 996) {
            url = this.$pageDongkuangDangerEquipmentAddOrUpdate;
            if (this.ids) {
              params["id"] = this.ids;
            }
          } else if (Number(this.menuId) == 977) {
            url = this.$mhqtzAddOrUpdate;
            if (this.ids) {
              params["id"] = this.ids;
            }
          }
          if (!url) {
            return;
          }
          this.loading = {
            ...this.loading,
            saveLoading: true,
          };
          this.postAxios(url, params)
            .then((res) => {
              if (res.code == 200) {
                this.$message.success({
                  content: res.msg || res.data,
                  duration: 2.5,
                });
                this.onRefresh();
                this.visible = false;
              } else {
                this.$message.error(res.msg || "操作失败,请稍后再试");
              }
            })
            .catch(() => { })
            .finally(() => {
              this.loading = {
                ...this.loading,
                saveLoading: false,
              };
            });
        }
      });
    },
    getHeadTitle() {
      let str;
      if (this.headTitle) {
        str = this.headTitle;
      } else if (this.menuId) {
        let menuArr = localStorage.getItem("menu") ? JSON.parse(localStorage.getItem("menu")) : [];
        let item = menuArr.find((val) => val.id == this.menuId);
        if (item) {
          str = item.name;
        }
      }
      let extra;
      if ([9, 13].includes(Number(this.menuId))) {
        extra = this.fromType == "edit" ? "编辑" : "新增";
      } else {
        extra = this.ids ? "编辑" : "新增";
      }
      this.drawerTitle = `${str ? str : ""}${str ? "-" : ""}${extra}`;
    },
    onValuesChange(props, values) {
      let newStr = JSON.stringify(values);
      let oldStr = JSON.stringify(this.formVal);
      if (newStr != oldStr) {
        this.isChange = true;
      }
    },
  },
  computed: {},
  watch: {
    visible: {
      handler(nVal, oVal) {
        if (!nVal) {
          this.formData = [];
          this.formVal = {};
          this.form.resetFields();
          this.isChange = false;
        }
      },
    },
  },
  created() {
    this.form = this.$form.createForm(this, {
      name: "advanced_search",
      onValuesChange: this.onValuesChange,
    });
  },
};
</script>
<style lang="less" scoped>
::v-deep {
  .ant-drawer-body {
    padding: 8px 12px;
  }
}

.drawContWrap {
  height: calc(100vh - 55px - 53px - 16px);
  overflow-x: hidden;
  overflow-y: auto;

  .spinWrap {
    width: 100%;
    height: 100%;
  }
}

.iconButton {
  cursor: pointer;
}

.no-border-button {
  border: none !important;
  /* 移除边框 */
  box-shadow: none !important;
  /* 移除阴影 */
}
</style>
